package com.lin.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @作者: 林江
 * @创建时间: 2024/2/12
 * @功能:
 */
@Controller
public class SsoServerController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping ("doLogin")
    public String auth(Model model, String username,
                       String password, String url,
                       HttpServletResponse resp) {
        System.out.println(username + ":" + password);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)
                || !username.equals("admin") || !password.equals("123456")) {
            model.addAttribute("data", url);
            return "login";
        } else {
            //说明登录成功
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token, "true");
            resp.addCookie(new Cookie("sso_cookie", token));
            return "redirect:" + url + "?token=" + token;
        }
    }

    @RequestMapping("login.html")
    public String login(Model model, @RequestParam(value = "redirect",required = false) String redirect,
                        @CookieValue(value = "sso_cookie", required = false) String ssoCooke) {
        if (!StringUtils.isEmpty(ssoCooke)) {
            // 如果同一个在进行登录第二个系统，那么就不需要在登录了。
            return "redirect:" + redirect + "?token=" + ssoCooke;
        }
        model.addAttribute("data", redirect);
        return "login";
    }
}
